# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        val = l1.val + l2.val
        l1 = l1.next if l1.next else ListNode(0)
        l2 = l2.next if l2.next else ListNode(0)
        l1.val += val//10  # integer division
        next_node = self.addTwoNumbers(l1, l2) \
            if l1.val or l1.next or l2.val or l2.next \
            else None
        return ListNode(val%10, next_node)


if __name__ == '__main__':
    def print_linked_list(listNode):
        def print_ll_helper(listNode):
            if listNode is None:
                return []
            return [listNode.val] + print_ll_helper(listNode.next)
        print(print_ll_helper(listNode))
    
    def init_linked_list(lst):
        if lst == []:
            return None
        return ListNode(lst[0], init_linked_list(lst[1:]))
    
    soln = Solution()
    # print_linked_list(init_linked_list([5,2,3]))
    print_linked_list(soln.addTwoNumbers(init_linked_list([1,2,3]), init_linked_list([2,3,4])))
    print_linked_list(soln.addTwoNumbers(init_linked_list([9,2,9]), init_linked_list([2,3,4])))
